package com.test.realcityalfa.frmwrk;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public abstract class CustomAsyncTask extends AsyncTask<Void, Object, Object> {
	private Context context;
	private ProgressDialog progressDialog;
	private ProgressBar progressBar;
	private String progressMessage;
	
	public CustomAsyncTask(Context context)
	{
		this.context = context;
	}
	public CustomAsyncTask(Context context, String progressMessage)
	{
		this.context = context;
		this.progressMessage = progressMessage;
	}
	
	public CustomAsyncTask(Context context, ProgressBar progressBar)
	{
		this.context = context;
		this.progressBar = progressBar;
	}
	
	protected abstract Object asyncOperation() throws Throwable;
	
	protected abstract void onResult(Object result) throws Exception;
	
	protected abstract void onProgress(Object update) throws Exception;
	
	@Override
	protected Object doInBackground(Void... params) {
		// TODO Auto-generated method stub
		try
		{
			return asyncOperation();
		}
		catch(Throwable e)
		{
			e.printStackTrace(System.err);
			return e;
		}		
	}	
	
	@Override
	protected void onCancelled() 
	{
		dismissDialog();
		super.onCancelled();
		
	}

	@Override
	protected void onPostExecute(Object result) 
	{
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		
		if(!(result instanceof Throwable))
		{
			try
			{
				onResult(result);
				return;
			}
			catch(Exception e)
			{
				result = e;
			}
			finally{dismissDialog();}
		}
		dismissDialog();
	}

	@Override
	protected void onPreExecute() 
	{		
		showDialog();
		super.onPreExecute();
	}

	@Override
	protected void onProgressUpdate(Object... values) 
	{
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
		try 
		{
			onProgress(values);
		} 
		catch (Exception e) 
		{		
			e.printStackTrace();
		}
	}
	
	
	protected void showDialog()
	{
		if(progressMessage != null)
		{
			progressDialog = ProgressDialog.show(context, null, progressMessage, true);
		}
		if(progressBar != null)
		{
			progressBar.setVisibility(View.VISIBLE);
		}
	}
	
	protected void dismissDialog()
	{
		if(progressDialog != null && progressDialog.isShowing())
		{
			progressDialog.dismiss();
			progressDialog = null;
		}
		if(progressBar != null)
		{
			progressBar.setVisibility(View.GONE);
		}
	}
	
	protected void showToastMessage(Object text)
	{
		Toast.makeText(context, text.toString(), Toast.LENGTH_LONG).show();
	}
	
}
